package net.thellium.ddiameter.protocol.avp.parser;

import java.util.Arrays;

import com.google.inject.Inject;

import net.thellium.ddiameter.protocol.AVP;
import net.thellium.ddiameter.protocol.AVPDictionary;
import net.thellium.ddiameter.protocol.avp.AvpFactory;
import net.thellium.ddiameter.protocol.avp.BaseAVP;
import net.thellium.ddiameter.protocol.dictonary.impl.AVPDictionaryImpl;

public class AVPParser {
	@Inject
	AVPDictionary dictionary;
	public AVP parseAVP(byte[] bytes) {
		int avpCode = (int) ParserUtils.bytesToLong(new byte[]{bytes[0],bytes[1],bytes[2],bytes[3]});
		byte flags = bytes[4];
		boolean vendorSpec = (flags & 0x80)== 0x80;
		boolean mandatory = (flags & 0x40)== 0x40;
		boolean encrypted = (flags & 0x20)== 0x20;
		long length = ParserUtils.bytesToLong(new byte[]{bytes[5],bytes[6],bytes[7]});
		Long vid = null;
		int dataStartIdx = 8;
		if (vendorSpec) {
			vid = ParserUtils.bytesToLong(new byte[]{bytes[8],bytes[9],bytes[10],bytes[11]});
			dataStartIdx+=4;
		}
		byte[] dataBytes=Arrays.copyOfRange(bytes, dataStartIdx, (int) length);
		AVPDictionary dictionary = new AVPDictionaryImpl();
		
		BaseAVP avp = AvpFactory.getAVP(dictionary.getTypeByAvpCode(avpCode), dataBytes);
		avp.setCode(avpCode);
		avp.setEncrypted(encrypted);
		avp.setMandatory(mandatory);
		avp.setVendorSpecific(vendorSpec);
		if (vendorSpec) avp.setVendorID(vid);
		return avp;
	}
}
